package com.cjl.demo.test;

/**
 * <p>Copyright: All Rights Reserved</p>
 * <p>Company:  两个有序数组的合并排序,Java代码实现,并去重复，考虑空间利用率问题  http://www.ronglian.com</p>
 * <p>Description:  </p>
 * <p>Author:jlchen/陈金梁</p>
 * <p>Date:  2018/3/25</p>
 */
public class SortTwoSortedArray {
    public static void main(String[] args) {
        int[] sortArray1 = {1, 3, 5, 7 ,8,10,15,17,};
        int[] sortArray2 = {2, 4, 6, 8, 10, 12};

        SortTwoSortedArrayWithEquals(sortArray1, sortArray2);
        System.out.println("**************");
        SortTwoSortedArrayWithoutEquals(sortArray1, sortArray2);

    }

    private static void SortTwoSortedArrayWithEquals(int[] sortArray1, int[] sortArray2) {
        int legth1 = sortArray1.length;
        int legth2 = sortArray2.length;
        int[] result = new int[legth1 + legth2];
        int i = 0, j = 0, k = 0;
        while (i < legth1 && j < legth2) {
            if (sortArray1[i] <= sortArray2[j]) {
                result[k++] = sortArray1[i++];
            } else {
                result[k++] = sortArray2[j++];
            }
        }

        for (; i < legth1;) {
            result[k++] = sortArray1[i++];
        }

        for (; j < legth2;) {
            result[k++] = sortArray2[j++];
        }

        for (int tmp : result) {
            System.out.println("args = [" + tmp + "]");
        }
    }

    private static void SortTwoSortedArrayWithoutEquals(int[] sortArray1, int[] sortArray2) {
        int legth1 = sortArray1.length;
        int legth2 = sortArray2.length;
        int[] result = new int[legth1 + legth2];
        int i = 0, j = 0, k = 0;
        while (i < legth1 && j < legth2) {
            if (sortArray1[i] < sortArray2[j]) {
                result[k++] = sortArray1[i++];
            } else if(sortArray1[i] == sortArray2[j]){
                result[k++] = sortArray2[j++];
                i++;
            }else {
                result[k++] = sortArray2[j++];
            }
        }

        while (i < legth1) {
            result[k++] = sortArray1[i++];
        }

        while (j < legth2) {
            result[k++] = sortArray2[j++];
        }

        for (int tmp : result) {
            System.out.println("args = [" + tmp + "]");
        }
    }
}
